package org.jeecg.modules.lab.entrust.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.lab.entrust.entity.LabEntrustItems;
import org.jeecg.modules.lab.entrust.entity.LabEntrustItemsIndex;
import org.jeecg.modules.lab.entrust.entity.LabEntrustSample;
import org.jeecg.modules.lab.entrust.entity.LabWsupervise;
import org.jeecg.modules.lab.entrust.mapper.LabEntrustItemsIndexMapper;
import org.jeecg.modules.lab.entrust.mapper.LabEntrustItemsMapper;
import org.jeecg.modules.lab.entrust.mapper.LabEntrustSampleMapper;
import org.jeecg.modules.lab.entrust.mapper.LabWsuperviseMapper;
import org.jeecg.modules.lab.entrust.service.ILabWsuperviseService;
import org.jeecg.modules.lab.items.entity.LabItems;
import org.jeecg.modules.lab.items.entity.LabItemsBasis;
import org.jeecg.modules.lab.items.entity.LabItemsBasisIndex;
import org.jeecg.modules.lab.items.entity.LabItemsRelevBasis;
import org.jeecg.modules.lab.items.ibasis.mapper.LabItemsBasisMapper;
import org.jeecg.modules.lab.items.item.mapper.LabItemsBasisIndexMapper;
import org.jeecg.modules.lab.items.item.mapper.LabItemsMapper;
import org.jeecg.modules.lab.items.item.service.ILabItemsService;
import org.jeecg.modules.lab.items.record.service.ILabItemsRecordNormService;
import org.jeecg.modules.lab.items.record.service.ILabItemsRecordPersonService;
import org.jeecg.modules.lab.items.record.service.ILabItemsRecordSampleService;
import org.jeecg.modules.lab.items.record.service.ILabItemsRecordTargetService;
import org.jeecg.modules.lab.items.relve.service.ILabItemsRelevBasisService;
import org.jeecg.modules.lab.sample.entity.LabSampleRecord;
import org.jeecg.modules.lab.sample.record.mapper.LabSampleRecordMapper;
import org.jeecg.modules.lab.util.FlowNumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 监督抽查表
 * @Author: jeecg-boot
 * @Date: 2023-09-18
 * @Version: V1.0
 */
@Service
public class LabWsuperviseServiceImpl extends ServiceImpl<LabWsuperviseMapper, LabWsupervise> implements ILabWsuperviseService {

    @Autowired
    private LabWsuperviseMapper labWsuperviseMapper;

    @Autowired
    private LabEntrustItemsMapper labEntrustItemsMapper;

    @Autowired
    private LabEntrustSampleMapper labEntrustSampleMapper;

    @Autowired
    private LabSampleRecordMapper labSampleRecordMapper;

    @Autowired
    private LabItemsMapper labItemsMapper;

    @Autowired
    private FlowNumberUtil flowNumberUtil;

    @Autowired
    private LabItemsBasisMapper labItemsBasisMapper;

    @Autowired
    private ILabItemsRecordSampleService labItemsRecordSampleService;

    @Autowired
    private ILabItemsRecordNormService labItemsRecordNormService;

    @Autowired
    private ILabItemsRecordTargetService labItemsRecordTargetService;

    @Autowired
    private ILabItemsRecordPersonService labItemsRecordPersonService;

    @Autowired
    private LabItemsBasisIndexMapper labItemsBasisIndexMapper;

    @Autowired
    private LabEntrustItemsIndexMapper labEntrustItemsIndexMapper;

    @Autowired
    private ILabItemsService labItemsService;

    @Autowired
    private ILabItemsRelevBasisService labItemsRelevBasisService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMain(LabWsupervise labWsupervise, List<LabEntrustSample> labSampleList) {
        labWsuperviseMapper.insert(labWsupervise);
        if (labSampleList != null && labSampleList.size() > 0) {
            for (LabEntrustSample entity : labSampleList) {
                //外键设置
                entity.setEntrustId(labWsupervise.getId());
                labEntrustSampleMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(LabWsupervise labWsupervise, List<LabEntrustSample> labSampleList) {
        labWsupervise.setSynFlag("1");
        labWsuperviseMapper.updateById(labWsupervise);
        //1.先删除子表数据
        labEntrustSampleMapper.deleteByMainId(labWsupervise.getId());
        //2.子表数据重新插入
        if (labSampleList != null && labSampleList.size() > 0) {
            for (LabEntrustSample entity : labSampleList) {
                //外键设置
                entity.setEntrustId(labWsupervise.getId());
                labEntrustSampleMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importSaveMain(List<LabWsupervise> wsuperviseList) {
        for (LabWsupervise labWsupervise : wsuperviseList) {
            String tailName= labWsupervise.getTailName();
            if (!"".equals(tailName) && tailName!=null && !tailName.contains("必填")) {
                String sampleType = labWsupervise.getSampleType();
                String sampleSort = labWsupervise.getSampleSort();
                String testItems = labWsupervise.getTestItems();
                if (!"".equals(sampleType) && sampleType != null) {
                    QueryWrapper<LabItems> typeWrapper = new QueryWrapper<>();
                    typeWrapper.clear();
                    typeWrapper.eq("name", sampleType);
                    List<LabItems> itemTypes = labItemsService.list(typeWrapper);
                    if (itemTypes.size() > 0) {
                        String typeId = itemTypes.get(0).getId();
                        labWsupervise.setSampleTypeId(typeId);
                        QueryWrapper<LabItems> sortWrapper = new QueryWrapper<>();
                        sortWrapper.clear();
                        sortWrapper.eq("name", sampleSort).eq("pid", typeId);
                        List<LabItems> itemSorts = labItemsService.list(sortWrapper);
                        if (itemSorts.size() > 0) {
                            String sortId = itemSorts.get(0).getId();
                            labWsupervise.setSampleSortId(sortId);
                            if (!"".equals(testItems)) {
                                List<String> itemList = Arrays.asList(testItems.split(","));
                                QueryWrapper<LabItems> itemsWrapper = new QueryWrapper<>();
                                itemsWrapper.clear();
                                itemsWrapper.in("name", itemList).eq("pid", sortId);
                                List<LabItems> labItems = labItemsService.list(itemsWrapper);
                                int num = labItems.size();
                                String[] itemsIds = new String[num];
                                String[] itemsNames = new String[num];
                                for (int i = 0; i < num; i++) {
                                    LabItems item = labItems.get(i);
                                    String itemId = item.getId();
                                    String itemName = item.getName();
                                    QueryWrapper<LabItemsRelevBasis> relevWrapper = new QueryWrapper<>();
                                    relevWrapper.clear();
                                    relevWrapper.eq("items_id", itemId).eq("core_flag","1");
                                    List<LabItemsRelevBasis> labItemsRelevBasisList = labItemsRelevBasisService.list(relevWrapper);
                                    if (labItemsRelevBasisList.size() > 0) {
                                        LabItemsRelevBasis relevBasis = labItemsRelevBasisList.get(0);
                                        String basisId = relevBasis.getBasisId();
                                        itemsIds[i] = "\"" + itemId + "-" + basisId + "\"";
                                        itemsNames[i] = "\"" + itemName + "\"";
                                    }
                                }
                                labWsupervise.setTestItemsIds("[" + String.join(",", itemsIds) + "]");
                                labWsupervise.setTestItems("[" + String.join(",", itemsNames) + "]");
                            }
                        }
                    }
                }
                labWsupervise.setSynFlag("0");
                labWsupervise.setAuditMark("制单中");
                labWsupervise.setAllotStatus("待分配");
                labWsupervise.setEntrustType("监督检验");
                labWsupervise.setCarryName("中国石油西南油气田分公司天然气研究院气田开发化学实验室");
                labWsupervise.setCarryAddress("四川省成都市天府新区华阳天研路218号610213");
                labWsupervise.setCarryContact("印 敬/(028)85604123 13880486175 张楠革/(028)85604594 13618090676");
                labWsupervise.setCodeRule("JXY");
                labWsuperviseMapper.insert(labWsupervise);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        labEntrustSampleMapper.deleteByMainId(id);
        labWsuperviseMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            labWsuperviseMapper.deleteById(id);
            labEntrustSampleMapper.deleteByMainId(id.toString());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditSupervise(LabWsupervise labWsupervise) {
        //1、更新主表
        labWsupervise.setAuditMark("审核通过");
        labWsupervise.setSynFlag("1");
        labWsuperviseMapper.updateById(labWsupervise);

        String taskId =labWsupervise.getId();
        //2、保存样品数据
        //先删除样品、再新增样品
        labEntrustSampleMapper.deleteByMainId(taskId);
        LabEntrustSample labEntrustSample = new LabEntrustSample();
        String samNum = flowNumberUtil.generateSerialNum("JXY", 1).get(0);
        labEntrustSample.setSamType("主剂");
        labEntrustSample.setSamNum(samNum);
        labEntrustSample.setSamName(labWsupervise.getTailName());
        labEntrustSample.setSamEnt(labWsupervise.getSpotEntName());
        labEntrustSample.setSamAddress(labWsupervise.getSpotAddress());
        labEntrustSample.setSamAppear(labWsupervise.getTailState());
        labEntrustSample.setSamNumber(labWsupervise.getSpotBase());
        labEntrustSample.setSamQuality(labWsupervise.getSpotAmount());
        labEntrustSample.setHandPerson(labWsupervise.getSpotPerson());
        labEntrustSample.setEntrustId(labWsupervise.getId());
        labEntrustSample.setLotNum(labWsupervise.getTailBatch());
        labEntrustSample.setModel(labWsupervise.getTailModel());
        labEntrustSample.setSamDate(String.valueOf(labWsupervise.getSpotDate()));
        labEntrustSample.setSamPack(labWsupervise.getTailPackage());
        labEntrustSample.setSamStatus("待检");
        labEntrustSample.setSynFlag("0");
        labEntrustSampleMapper.insert(labEntrustSample);

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String realname = loginUser.getRealname();
        //3、样品流转记录
        //先删除记录、再新增记录
        labSampleRecordMapper.deleteById(taskId);
        LabSampleRecord labSampleRecord = new LabSampleRecord();
        labSampleRecord.setSamType("主剂");
        labSampleRecord.setSamId(labEntrustSample.getId());
        labSampleRecord.setSamName(labEntrustSample.getSamName());
        labSampleRecord.setSamNum(labEntrustSample.getSamNum());
        labSampleRecord.setRecordMark("入库");
        labSampleRecord.setReceivePerson(realname);
        labSampleRecord.setOperatePerson(realname);
        labSampleRecord.setRecordTime(new DateTime());
        labSampleRecord.setBusId(labEntrustSample.getEntrustId());
        labSampleRecord.setSynFlag("0");
        labSampleRecord.setRecordRemark(labSampleRecord.getRecordTime() + "" + realname + "进行样品登记入库。");
        labSampleRecordMapper.insert(labSampleRecord);


        //4、保存项目数据
        //先删除、再新增
        labEntrustItemsMapper.deleteByTaskId(taskId);
        labEntrustItemsIndexMapper.deleteByTaskId(taskId);
        labItemsRecordSampleService.deleteByTaskId(taskId);
        labItemsRecordNormService.deleteByTaskId(taskId);
        labItemsRecordTargetService.deleteByTaskId(taskId);
        labItemsRecordPersonService.deleteByTaskId(taskId);
        String itemsIds = labWsupervise.getTestItemsIds().replace("[", "").replace("]", "").replace("\"", "");
        if (itemsIds != null && itemsIds != "") {
            ArrayList listIds = new ArrayList(Arrays.asList(itemsIds.split(",")));
            for (int i = 0; i < listIds.size(); i++) {
                String item_basis_id = listIds.get(i).toString();
                ArrayList ids = new ArrayList(Arrays.asList(item_basis_id.split("-")));
                String item_id = String.valueOf(ids.get(0));
                String basis_id = "";
                //兼容历史数据
                if (ids.size() > 1) {
                    basis_id = String.valueOf(ids.get(1));
                }
                LabItems entity = labItemsMapper.selectById(item_id);

                LabEntrustItems labEntrustItems = new LabEntrustItems();
                labEntrustItems.setEntrustId(labWsupervise.getId());
                labEntrustItems.setItemId(entity.getId());
                labEntrustItems.setItemName(entity.getName());
                //项目标准数据
                if (basis_id != null && !"".equals(basis_id)) {
                    LabItemsBasis labItemsBasis = labItemsBasisMapper.selectById(basis_id);
                    if (labItemsBasis != null) {
                        labEntrustItems.setBasisId(basis_id);
                        labEntrustItems.setBasisName(labItemsBasis.getName());
                        labEntrustItems.setBasisNum(labItemsBasis.getNum());
                        labEntrustItems.setBasisScope(labItemsBasis.getScope() == null ? "" : labItemsBasis.getScope());
                        labEntrustItems.setBasisAtta(labItemsBasis.getAtta() == null ? "" : labItemsBasis.getAtta());
                    }
                }

                labEntrustItems.setTeam(entity.getTeam());
                labEntrustItems.setPrintMark(entity.getPrintMark());
                labEntrustItems.setBigTypeId(labWsupervise.getSampleTypeId());
                labEntrustItems.setBigTypeName(labWsupervise.getSampleType());
                labEntrustItems.setMidTypeId(labWsupervise.getSampleSortId());
                labEntrustItems.setMidTypeName(labWsupervise.getSampleSort());
                labEntrustItems.setItemStatus("待分配");
                labEntrustItems.setSamId(labEntrustSample.getId());
                labEntrustItems.setSamName(labEntrustSample.getSamName());
                labEntrustItems.setSamNum(labEntrustSample.getSamNum());
                labEntrustItems.setEntrustType("监督抽查");
                labEntrustItems.setSignatureStatus("待同步签名");
                labEntrustItems.setSynFlag("0");
                //添加项目的标准和标准类型
                labEntrustItemsMapper.insert(labEntrustItems);

                //根据项目id+标准id查询检测指标，如果没有再根据项目id查询检测指标
                QueryWrapper<LabItemsBasisIndex> queryWrapper = new QueryWrapper<>();
                queryWrapper.clear();
                queryWrapper.eq("items_id", item_id);
                queryWrapper.eq("basis_id", basis_id);
                List<LabItemsBasisIndex> labItemsBasisIndexList = labItemsBasisIndexMapper.selectList(queryWrapper);
                if (labItemsBasisIndexList == null) {
                    queryWrapper.clear();
                    queryWrapper.eq("items_id", item_id);
                    queryWrapper.isNull("basis_id");
                    labItemsBasisIndexList = labItemsBasisIndexMapper.selectList(queryWrapper);
                } else {
                    for (LabItemsBasisIndex index : labItemsBasisIndexList) {
                        LabEntrustItemsIndex labEntrustItemsIndex = new LabEntrustItemsIndex();
                        labEntrustItemsIndex.setTaskId(labWsupervise.getId());
                        labEntrustItemsIndex.setTaskItemsId(labEntrustItems.getId());
                        labEntrustItemsIndex.setItemId(item_id);
                        labEntrustItemsIndex.setBasisId(basis_id);
                        labEntrustItemsIndex.setIndexName(index.getIndexName());
                        labEntrustItemsIndex.setIndexCode(index.getIndexCode());
                        labEntrustItemsIndex.setIndexBasis(index.getIndexBasis());
                        labEntrustItemsIndex.setIndexType(index.getIndexType());
                        labEntrustItemsIndex.setSynFlag("0");
                        labEntrustItemsIndexMapper.insert(labEntrustItemsIndex);
                    }
                }

                //插入项目模板-样品信息
                labItemsRecordSampleService.insertSamData(labEntrustItems);
                //插入项目模板-检测条件信息
                labItemsRecordNormService.insertNormData(labEntrustItems);
                //插入项目模板-检测信息
                labItemsRecordTargetService.insertTargetData(labEntrustItems);
                //插入项目模板-人员信息
                labItemsRecordPersonService.insertPersonData(labEntrustItems);

            }
        }
    }

}
